<template>
  <div>
    <el-tree
      ref="refTree"
      :data="list"
      :default-expand-all="true"
      show-checkbox
      check-strictly
      :props="{label: 'name'}"
      node-key="id"
    />

    <el-button size="small" @click="hClose">取消</el-button>
    <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permissions'
import { getRoleDetail, assignPerm } from '@/api/settings'
import { tranListToTreeData } from '@/utils'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()
    this.loadRoleDetail()
  },
  methods: {
    hClose() {
      this.$emit('close')
    },
    // 获取角色现有的权限
    async loadRoleDetail() {
      const res = await getRoleDetail(this.roleId)
      console.log('获取角色现有的权限', res.data.permIds)

      // 回填
      this.$refs.refTree.setCheckedKeys(res.data.permIds)
    },
    // 获取系统中全部的权限
    async loadPermissionList() {
      const res = await getPermissionList()
      // 数据格式处理： 数组变成树状的数据
      this.list = tranListToTreeData(res.data)
      console.log('loadPermissionList', this.list)
    },
    async hSubmit() {
      // 如何从tree中取出选中的ids ？
      const permIds = this.$refs.refTree.getCheckedKeys()
      // console.log(permIds)
      const res = await assignPerm({ id: this.roleId, permIds })

      console.log('保存权限', res)
      this.$message.success('保存权限成功')
      this.$emit('close')
    }
  }
}
</script>
